package com.waya.web.browser.common.util;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.waya.web.browser.common.show.FL;
import com.waye.wanba.utils.APPLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by JesseHev on 2018/1/16.
 * describe: 下载工具类（不支持断点、多线程、下载进度）
 */

public class DownloadUtil {

    private static final String TAG = "DownloadUtil";
    private static final int TIMEOUT = 10;
    private Handler mHandler;
    private static volatile DownloadUtil INSTANCE = null;

    private DownloadUtil() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static DownloadUtil getInstance() {
        if (INSTANCE == null) {
            synchronized (DownloadUtil.class) {
                INSTANCE = new DownloadUtil();
            }
        }
        return INSTANCE;
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(TIMEOUT, TimeUnit.SECONDS);
        builder.connectTimeout(TIMEOUT, TimeUnit.SECONDS);
        return builder.build();
    }

    /**
     * 下载文件
     *
     * @param url  文件url
     * @param file 存储目标目录
     */
    public void download(String url, final File file, final AbsResponse callBack) {
        final Request request = new Request.Builder().url(url).build();
        final Call call = getOkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.toString());
                setOnError(e.getMessage(), callBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    long total = response.body().contentLength();
                    APPLog.printDebug("文件总长度===》" + total + "转化后的文件大小==》" + AndroidUtils.formatFileSize(total));
                    long current = 0;
                    is = response.body().byteStream();
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        current += len;
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    if (current != total) {
                        FL.e(TAG, "文件下载不完整...");
                        setOnError("文件下载不完整...", callBack);
                        return;
                    }
                    APPLog.printInfo("文件下载完成，总大小==》" + AndroidUtils.formatFileSize(current));
                    setOnResponse(file.getAbsolutePath(), callBack);
                } catch (IOException e) {
                    Log.e(TAG, e.toString());
                    setOnError(e.getMessage(), callBack);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, e.toString());
                    }
                }
            }
        });
    }

    private void setOnError(final String error, final IResponse response) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                response.onError(error);
            }
        });
    }

    private void setOnResponse(final String data, final IResponse response) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                response.onResponse(data);
            }
        });
    }


    public static class AbsResponse implements IResponse {

        @Override
        public void onResponse(String data) {

        }

        @Override
        public void onError(String error) {

        }
    }
}
